<?php
/**
 * @author fyl
 * Date: 16-11-18
 */
class UserService extends BaseService
{
    private static $self           =   NULL;
    private $mUser                 =   NULL;
    private $mUserMessage          =   NULL;
    private $mUserAward            =   NULL;
    private $mUserTicket           =   NULL;
    private $mDealDeposit          =   NULL;
    private $mUserFund             =   NULL;
    private $mUserLock             =   NULL;
    private $mRefundPlan           =   NULL;
    private $mBankCard             =   NULL;
    private $mExperRecord          =   NULL;
    private $mInvest               =   NULL;

    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }

    public function __construct()
    {
        $this->mUser                   =   new Involved_UserModel();
        $this->mUserMessage            =   new Involved_UserMessageModel();
        $this->mUserTicket             =   new Involved_UserTicketModel();
        $this->mUserAward              =   new Involved_UserAwardModel();
        $this->mDealDeposit            =   new Involved_DealDepositModel();
        $this->mUserFund               =   new Involved_UserFundModel();
        $this->mUserLock               =   new Involved_UserLockModel();
        $this->mRefundPlan             =   new Involved_RefundPlanModel();
        $this->mBankCard               =   new Involved_BankCardModel();
        $this->mExperRecord            =   new Involved_ExperRecordModel();
        $this->mInvest                 =   new Involved_InvestModel();
    }


    /**
     * 用户列表
     * @return mixed
     */
    public function ManageUser()
    {
        return $this->mUser->ManageUserList();

    }

    /**
     * 用户总盈利
     * @return mixed
     */
    public function UserAmountAll()
    {
        $refundPlan = $this->mRefundPlan->RefundPlanAll();
        $awardAmount = $this->mUserAward->AwardAmountAll();
        $UserAmountAll = $refundPlan+$awardAmount;
        return $UserAmountAll;
    }



//    /**
//     * 用户添加
//     * @param $paramObj
//     * @return int
//     * @throws Exception
//     */
//    public function UserAdd($paramObj)
//    {
//        if(empty($paramObj->password))
//            return Redirect::to('/add_user');
//        if($paramObj->password!==$paramObj->sure)
//            return Redirect::to('/add_user');
//        $salt  =  rand(100000, 999999);
//        $aData = [
//            'user_name'        =>    'GP'.time(),
//            'telephone'        =>    $paramObj->telephone,
//            'password'         =>    UserEnum::get(md5(md5($paramObj->password)),$salt),
//            'salt'             =>    $salt,
//            'add_time'         =>    time(),
//            'is_idcard'        =>    0,
//            'is_locked'        =>    0,
//        ];
//        return $this->mUser->insert($aData);
//    }


    /**
     * 用户信息
     * @return mixed
     */
    public function UserInfo($user_id)
    {
        return $this->mUser->UserInfo($user_id);
    }

    /**
     * 用户添加
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function UserAdd($paramObj)
    {
        if(empty($paramObj->password))
            return Redirect::to('/add_user');
        if($paramObj->password!==$paramObj->sure)
            return Redirect::to('/add_user');
        $salt  =  rand(100000, 999999);
        $aData = [
            'user_name'        =>    'GP'.time(),
            'telephone'        =>    $paramObj->telephone,
            'password'         =>    UserEnum::get(md5(md5($paramObj->password)),$salt),
            'salt'             =>    $salt,
            'add_time'         =>    time(),
            'is_idcard'        =>    0,
            'is_locked'        =>    0,
        ];
        $user_id = DB::table('user')->insertGetId($aData);
        // 添加默认资产数据
        $this->mUserFund->insert(['user_id' => $user_id]);
        return $this->run($user_id);
    }

    /**
     * 用户锁定
     * @return mixed
     */
    public function UserLocked($paramObj)
    {
        $data = [
            'is_locked' => $paramObj->status,
        ];
       $status = DB::table('user')
            ->where('user_id', $paramObj->user_id)
            ->update($data);
        if($status){
            return 200;
        }
    }


    /**
     * @param $user
     * @return bool
     * 注册红包生成
     */
    public function run($user)
    {
        if (!$user)
        {
            return false;
        }

        // 获取注册红包规则
        $regAwardRule = AwardEnum::getRegister();
        // 循环添加红包
        foreach ($regAwardRule as $key => $value)
        {
            $award = [
                'user_id' => $user,
                'amount'  => $value['amount']*100,
                'road'    => 'REGISTER',
                'status'  => 'AVAILABLE',
                'restrict_amount' => $value['restrict']*100,
                'due_time'=> strtotime(date('Y-m-d'))+$value['duetime'],
                'limit'   => $value['limit'],
                'add_time'=> time(),
            ];
            $this->mUserAward->insert($award);
        }

    }


    /**
     * 用户消息列表
     * @return mixed
     */
    public function UserMessage()
    {
        return $this->mUserMessage->UserMessageList();
    }

    /**
     * 用户消息添加
     * @param $paramObj
     * @return int
     */
    public function EditUserMessage($paramObj)
    {

        if(!empty($paramObj->user_id)){
            $aData = [
                'title'         => $paramObj->title,
                'content'       => $paramObj->content,
                'user_id'       => $paramObj->user_id,
                'is_read'       => 0,
                'is_valid'      => 1,
                'add_time'      => time()
            ];
            return $this->mUserMessage->insert($aData);
        }else{
            $AllId = $this->mUser->GetUserIdAll();
            foreach($AllId as $v){
                $aData = [
                    'title'         => $paramObj->title,
                    'content'       => $paramObj->content,
                    'user_id'       => $v->user_id,
                    'is_read'       => 1,
                    'is_valid'      => 1,
                    'add_time'      => time()
                ];
                $this->mUserMessage->insert($aData);
            }
            return true;
        }
    }

public function AdminGetUserInfo($id)
{
    $user_info = $this->mUser->GetUserInfo($id);
    $user_info->add_time = date('Y-m-d H:i:s',$user_info->add_time);
    $user_explain = [
        'user_id'   => '用户ID',
        'user_name' => '用户名称',
        'name'      => '真实姓名',
        'is_idcard' => '是否已实名认证',
        'idcard'    => '身份证',
        'telephone' => '手机号码',
        'add_time'  => '添加时间',
        'password'  => '用户密码'
    ];
    $data = [
        'topInfo'   => '用户ID:'.$id,
        // 项目附加数据
        'user_info'      => $user_info,
        // 字段说明
        'fieldInfo' => $user_explain,
    ];
    return $data;
}

    /**
     * 查询出用户红包与加息券数据
     */
    public function UserAwardInfo($id)
    {

        // 获取红包总数
        $anum   = $this->mUserAward->AwardCount($id);
        // 获取红包数据
        $award  = $this->mUserAward->GetUserAward($id);

        // 获取加息劵总数
        $tnum   = $this->mUserTicket->TicketCount($id);
        // 获取加息劵数据
        $ticket = $this->mUserTicket->GetUserTicket($id);

        //红包的数据说明
        $awardInfo = [
            'auto_id'         => '红包的ID',
            'user_id'         => '用户的ID',
            'trade_num'       => '投资订单号',
            'amount'          => '红包金额',
            'restrict_amount' => '投资激活限制金额',
            'road'            => '红包获取路径',
            'status'          => '红包状态',
            'active_time'     => '激活时间',
            'due_time'        => '红包到期时间',
            'add_time'        => '添加时间',
        ];


        //红包转化数据类型
        foreach ($award as $key => &$value)
        {
            // 激活时间
            if ($value->active_time!=0)
            {
                $value->active_time = date('Y-m-d H:i:s', $value->active_time);
            }

            // 红包到期时间
            $value->due_time        = date('Y-m-d H:i:s', $value->due_time);
            // 红包添加时间
            $value->add_time        = date('Y-m-d H:i:s', $value->add_time);
            // 红包获取路径
            $value->road            = UserEnum::road()[$value->road];
            // 红包状态
            $value->status          = UserEnum::status()[$value->status];
            // 红包金额
            $value->amount          = number_format($value->amount/100, 2).'元';
            // 投资激活限制金额
            $value->restrict_amount = number_format($value->restrict_amount/100, 2).'元';

        }
        unset($value);

        //加息劵的数据说明
        $ticketInfo = [
            'auto_id'     => '加息劵ID',
            'user_id'     => '用户ID',
            'rate'        => '加息劵利率',
            'road'        => '加息券获取途径',
            'status'      => '加息劵是否已使用',
            'active_time' => '激活时间',
            'due_time'    => '加息劵到期时间',
            'add_time'    => '添加时间',
        ];

        //加息劵转化数据
        foreach ($ticket as $key => &$value)
        {
            // 激活时间
            if ($value->active_time!=0)
            {
                $value->active_time = date('Y-m-d H:i:s', $value->active_time);
            }
            // 加息劵到期时间
            $value->due_time        = date('Y-m-d H:i:s', $value->due_time);
            // 加息劵添加时间
            $value->add_time        = date('Y-m-d H:i:s', $value->add_time);
            // 加息卷获取路径
            $value->road            = UserEnum::road()[$value->road];
            // 加息劵状态
            $value->status          = UserEnum::status()[$value->status];
        }
        unset($value);
        //将数据分配到数组中
        $tpldata = [
            // 红包数量
            'topInfo'    => '红包总数:'.$anum.'加息劵总数'.$tnum,
            // 红包的数据
            'award'      => $award,
            // 加息劵的数据
            'ticket'     => $ticket,
            // 红包的字段信息
            'awardInfo'  => $awardInfo,
            // 加息劵的字段信息
            'ticketInfo' => $ticketInfo,
        ];
        return $tpldata;
    }


    /**
     * 充值列表
     */
    public function UserDepositInfo($user_id)
    {
        //充值信息
        $info = $this->mDealDeposit->GetUserDeposit($user_id);
        //充值总金额
        $sum_price = $this->mDealDeposit->GetUserDepositSum($user_id);

        //充值记录转化数据类型
        foreach ($info as $key => &$value)
        {
            // 充值金额
            $value->amount          = number_format($value->amount/100, 2).'元';
            // 手续费
            $value->fee             = number_format($value->fee/100, 2).'元';
            //支付类型
            $value->pay_type        = DepositEnum::pay_type()[$value->pay_type];
            //支付方式
            $value->pay_way         = DepositEnum::pay_way()[$value->pay_way];
            //业务类型
            $value->detail          = DepositEnum::detail()[$value->detail];
            //状态
            $value->status          = DepositEnum::status()[$value->status];
            //完成时间
            $value->finish_time     = date('Y-m-d H:i:s',$value->finish_time);
            //添加时间
            $value->add_time        = date('Y-m-d H:i:s',$value->add_time);
        }

        $deposit = [
            'auto_id'           =>      '订单ID',
            'trade_num'         =>      '订单号码',
            'user_id'           =>      '用户ID',
            'plf_num'           =>      '平台流水号',
            'amount'            =>      '充值金额',
            'fee'               =>      '手续费',
            'pay_type'          =>      '支付类型',
            'pay_way'           =>      '支付方式',
            'device'            =>      '交易发起端',
            'note'              =>      '支付备注',
            'detail'            =>      '业务类型',
            'status'            =>      '订单状态',
            'finish_time'       =>      '完成时间',
            'add_time'          =>      '添加时间',

        ];
        $data = [
            'topInfo'       => '总金额:'.number_format($sum_price/100,2).'元',
            'info'          => $info,
            'deposit_info'   => $deposit
        ];
        return $data;
    }


    /**
     * @param $user_id
     * @return bool
     * 根据用户ID取得用户资产数据
     */
    public function GetFund($user_id)
    {
        if (!$user_id)
        {
            return false;
        }

        $fund = $this->mUserFund->GetFund($user_id);

        // 可用余额
        $fund->money = $fund->money_deposit+$fund->money_award+$fund->money_return;

        // 可用余额转换分为元
        $fund->money_unit   = $fund->money/100;
        $fund->money_format = number_format($fund->money/100, 2);
        return $fund;
    }

    /**
     * @param $id
     * @return array
     * 获取用户资金
     */
    public function GetUserFund($id)
    {
        $fundValue = $this->mUserFund->GetUserFund($id);
        // 数据说明
        $fieldInfo = [
            'user_id'       => '用户ID',
            'money_deposit' => '充值未投资金额',
            'money_award'   => '红包金额',
            'money_return'  => '回款金额',
            'money_freeze'  => '冻结金额',
            'money_invest'  => '可用余额',
            'money_unit'    => '格式化的可用余额',
            'money_format'  => '用户能使用的金额',
            'add_time'      => '添加时间'
        ];

        // 数据转换
        // 充值未投资金额
        $fundValue->money_deposit = number_format($fundValue->money_deposit/100, 2).'元';
        // 红包金额
        $fundValue->money_award   = number_format($fundValue->money_award/100, 2).'元';
        // 回款金额
        $fundValue->money_return  = number_format($fundValue->money_return/100, 2).'元';
        // 冻结金额
        $fundValue->money_freeze  = number_format($fundValue->money_freeze/100, 2).'元';
        // 在投金额
        $fundValue->money_invest  = number_format($fundValue->money_freeze/100, 2).'元';
        // 拼装发送视图的数组
        $tpldata = [
            // 头部信息
            'topInfo'    => '个人小资产',
            // 字段信息
            'fieldInfo'  => $fieldInfo,
            // 数据信息
            'data'       => $fundValue
        ];
        return $tpldata;
    }

    /**
     *判断处理
     *xf
     **/
    public  function Userlogin($paramObj){
        //php判断是否为空
        if(!preg_match("/^1[34578]{1}\d{9}$/",$paramObj->phones)) {
            $mess['code'] = '2';
            $mess['mess'] = '请输入正确的手机号';
            return $mess;
        }
        //php是否存在
        $data=$this->mUser->UserFirphone($paramObj->phones);
        if(empty($data->user_id)){
            $mess['code'] = '2';
            $mess['mess'] = '用户不存在';
            return $mess;
        }
        //是不是后台禁止登陆
        if($data->is_locked=='1'){
            $mess['code'] = '2';
            $mess['mess'] = '对不起，您的账号已被限制，请联系客服';
            return $mess;
        }
        $Lookcishu  =$this->mUserLock->LockUsercishu($data->user_id);//获取登陆次数
        if(!empty($Lookcishu)){
            $daes=strtotime(date('Ymd',$Lookcishu->lock_time)) + 86400;
            if(time()>$daes){
                $LookUseraaaa=$this->mUserLock->delete(['user_id'=>$Lookcishu->user_id]);
            }
        }
        $LookUsers  =$this->mUserLock->LockUser($data->user_id);//获取人是不是本冻结
        if(!empty($LookUsers)){//如果被冻结，看是否到解锁时间
            $LookUsersa  =$this->mUserLock->LockUserfirst ($data->user_id);
            if(time()<$LookUsersa->lock_time){
                $mess['code'] = '2';
                $mess['mess'] = '对不起，您的账户已被锁定,请于'.date('H:i:s',$LookUsersa->lock_time).'后尝试登录！';
                return $mess;
            }else{
                $LookUseraaaa=$this->mUserLock->delete(['user_id'=>$data->user_id]);
            }
        }
        //加密判断
        $psswd=UserEnum::get(md5(md5($paramObj->pwd)),$data->salt);//加密方式
        if($psswd==$data->password){
            #存储SESSION
            Session::put(UserEnum::USER_INFO_USER_ID, $data->user_id);
            Session::put(UserEnum::USER_INFO_SESSION_KEY, $data);
            if($paramObj->remember=='true'){
                setcookie('user_name',$paramObj->phones,time()+604800);
            }else{
                setcookie("user_name");
            }
            Session::put('login_time', time());//记录登录时间
            Session::forget('token');
            setcookie('login_time',time(),time()+60*30);
            //$LookUseraaaa=$this->mUserLock->delete(['user_id'=>$data->user_id]);
            $mess['code'] = '1';
            $mess['mess'] = '登陆成功';
            return $mess;
        }else{
            $LookUser =$this->mUserLock->LockUserfirst($data->user_id);

            if(!empty($LookUser->number)){
                $count = $LookUser->number;
                if($count<= 4){
                    $count--;
                    $logins=$count;
                    $array=array(
                        'number'    =>$logins,
                        'user_id'   =>$data->user_id,
                        'lock_time'  =>time(),
                        'ip'        =>$_SERVER['REMOTE_ADDR'],
                    );
//                    if ($count<1) {
//                        $LookUserd= $this->mUserLock->insert($array);
//                    }
                    if ($count>=0&&$count<=4) {
                        $LookUserd= $this->mUserLock->update($array,['lock_id' => $LookUser->lock_id]);
                    }
                }
                if($count == 0){
                    $data4['number'] = $count;
                    $data4['user_id'] = $data->user_id;
                    $data4['lock_time'] = time()+60*30;
                    $data4['ip'] = $_SERVER['REMOTE_ADDR'];
                    $LookUserd= $this->mUserLock->update($data4,['lock_id' => $LookUser->lock_id]);
                    if (!empty($LookUserd)) {
                        $mess['code'] = '2';
                        $mess['mess'] = '您已经连续5次输入错误密码，账户被锁定30分钟';
                        return $mess;
                    }
                }
                $mess['code'] = '3';
                $mess['mess'] = '"密码有误，请重新输入,今天还剩'.$count.'次';
                return $mess;
            }else{
                $logins=4;
                $array=array(
                    'number'    =>$logins,
                    'user_id'   => $data->user_id,
                    'lock_time'  =>time(),
                    'ip'        =>$_SERVER['REMOTE_ADDR'],
                );
                $LookUserd= $this->mUserLock->insert($array);
            }
            if (empty($LookUser->number)){
                $mess['code'] = '3';
                $mess['mess'] = "密码有误，请重新输入，今天还剩4次机会";
                return $mess;
            }

        }

    }

    /**
    *个人中心修改密码
     * xf
     */
    public function UserUpdatePwd($paramObj){
        //验证密码还原始密码是不是一样
        $user_info = session_get(UserEnum::USER_INFO_SESSION_KEY);
        $psswd=UserEnum::get(md5(md5($paramObj->pwd)),$user_info->salt);//加密方式
        if($psswd!=$user_info->password){
            $mess['code'] = '2';
            $mess['mess'] = '对不起，原密码不对';
            return $mess;
        }
        if($paramObj->newpwd!=$paramObj->surenewpwd){
            $mess['code'] = '2';
            $mess['mess'] = '对不起，两次输入密码不一致';
            return $mess;
        }
        //新的密码加密
        $salt  =  rand(100000, 999999);
        $newpsswd=UserEnum::get(md5(md5($paramObj->newpwd)),$salt);//加密方式
        $pwddata=array(
            'password'=>$newpsswd,
            'salt'=>$salt,
        );
       $deta= $this->mUser->update($pwddata,['user_id'=>$user_info->user_id]);
        if(!empty($deta)){
            Session::flush();
            $mess['code'] = '1';
            return $mess;
        }else{
            $mess['code'] = '2';
            $mess['mess'] = '修改失败';
            return $mess;
        }

    }
    public  function Userfirst(){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        if(!empty($user_id)){
            return $this->mUser->GetUserInfo($user_id);
        }
    }

    /**
     *个人中心实名认证
     * xf
     */
    public function UserAccoName($paramObj){
        //验证密码还原始密码是不是一样
        $user_info = session_get(UserEnum::USER_INFO_SESSION_KEY);
        if(empty($paramObj->sureuser)||empty($paramObj->idcard)){
            $mess['code'] = '2';
            $mess['mess'] = '用户名或身份证不能为空';
            return $mess;
        }
        $pwddata=array(
            'name'=>$paramObj->sureuser,
            'idcard'=>$paramObj->idcard,
            'is_idcard'=>1,
        );
        $deta= $this->mUser->update($pwddata,['user_id'=>$user_info->user_id]);
        if(!empty($deta)){
            $user_id=session_get(UserEnum::USER_INFO_USER_ID);
            $user_info = $this->mUser->GetUserInfo($user_id);
            Session::put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
            $mess['code'] = '1';
            return $mess;
        }else{
            $mess['code'] = '2';
            $mess['mess'] = '修改失败';
            return $mess;
        }

    }

    /**
     *忘记密码
     * xf
     */
    public function ForgetUpdatePwd($paramObj,$userinfo){
        if($paramObj->newpwd!=$paramObj->surenewpwd){
            $mess['code'] = '2';
            $mess['mess'] = '对不起，两次输入密码不一致';
            return $mess;
        }
        //新的密码加密
        $salt  =  rand(100000, 999999);
        $newpsswd=UserEnum::get(md5(md5($paramObj->newpwd)),$salt);//加密方式
        $pwddata=array(
            'password'=>$newpsswd,
            'salt'=>$salt,
        );
        $deta= $this->mUser->update($pwddata,['user_id'=>$userinfo->user_id]);
        if(!empty($deta)){
            Session::forget('token');
            $mess['code'] = '1';
            $mess['url'] = '/forget_compt.html';
            return $mess;
        }else{
            $mess['code'] = '2';
            $mess['mess'] = '修改失败';
            return $mess;
        }

    }
    /**
     *个人中心修改手机号
     * xf
     */
    public function UserAccoAjaxNewPhone($paramObj){
        if(empty($paramObj->mobile)){
            $mess['code'] = '2';
            $mess['mess'] = '请输入正确的手机号';
            return $mess;
        }
        $pwddata=array(
            'telephone'=>$paramObj->mobile,
        );
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $deta= $this->mUser->update($pwddata,['user_id'=>$user_id]);
        if(!empty($deta)){
            $mess['code'] = '1';
            return $mess;
        }else{
            $mess['code'] = '2';
            $mess['mess'] = '修改失败';
            return $mess;
        }

    }

    /**
    *查询手机号是不是存在
     **/
    public  function Userfirstphone($paramObj){
        //php判断是否为空
        if(!preg_match("/^1[34578]{1}\d{9}$/",$paramObj->mobile)) {
            $mess['code'] = '2';
            $mess['mess'] = '请输入正确的手机号';
            return $mess;
        }
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);

        $data=$this->mUser->UserFirphone($paramObj->mobile);
        if(empty($data)){
            $mess['code'] = '2';
            $mess['mess'] = '手机号还没有注册';
            return $mess;
        }
        if(strtolower($paramObj->captcha) != strtolower(Session::get('qt_Captcha'))){
            $mess['code'] = '2';
            $mess['mess'] = '验证码错误';
            return $mess;
        }else{
            return 1;
        }
    }



    public function UserAccounts($user_id){
        // 获取个人资产
        $fund = $this->GetFund($user_id);
        // 已激活红包金额
        $awardAmount = $this->mUserAward->AwardAmount($user_id);
        //获取未使用红包个数
        $awardNum = $this->mUserAward->AwardNum($user_id);
        //获取未使用加息券个数
        $TicketNum = $this->mUserTicket->TicketNum($user_id);
        // 代收本息
        // 回款计划
        $refundPlan = $this->mRefundPlan->RefundPlan($user_id);

        // 等待回款本金
        $waitRefundCapital = 0;
        // 等待回款利息
        $waitRefundAccrual = 0;
        // 已回款利息
        $refundAccrual     = 0;
        // 待回款总金额
        $waitRefundTotalAmount = 0;
        // 已回款总金额
        $refundTotalAmount = 0;
        // 累计收益
        $pileRefundAmount  = 0;
        // 已回款日历数据
        $refundCanlendar   = [];
        //体验金盈利

        // 当前月份
        $nowMonth = getdate()['mon'];

        // 本月还款笔数
        $monthRefundCount  = 0;
        // 本月还款金额
        $monthRefundAmount = 0;

        //体验表
        $TiyanItem = $this->mExperRecord->MonthTiyan($user_id);
        if($TiyanItem){
           $TiyanItem= $TiyanItem->return_money;
        }else{
            $TiyanItem = '0';
        }
        foreach ($refundPlan as $key => &$value)
        {
            $value->totalAmount = $value->amount_capital + $value->amount_accrual;
            $value->refund_time_text = date('Y-m-d', $value->refund_time);

            if ($value->status == 0)
            {
                $waitRefundCapital += $value->amount_capital;
                $waitRefundAccrual += $value->amount_accrual;
                $waitRefundTotalAmount += $value->totalAmount;
            }
            else
            {
                $refundTotalAmount += $value->totalAmount;
                $refundAccrual     += $value->amount_accrual;
            }
            $refundMonth = getdate($value->refund_time)['mon'];

            if ($nowMonth == $refundMonth)
            {
                $monthRefundCount++;
                $monthRefundAmount += $value->totalAmount;
            }
        }
        unset($value);

        // 基本资产组成
        $myFund = [
            // 可用余额
            'money'                 => $fund->money,
            // 待收本金
            'capital'               => $waitRefundCapital,
            // 待收利息
            'accrual'               => $waitRefundAccrual,
            // 已回款利息
            'refundAccrual'         => $refundAccrual,
            // 冻结金额
            'money_freeze'          => $fund->money_freeze,
            // 累计收益
            'totalAccrual'          => $pileRefundAmount,
            // 待回款总金额
            'waitRefundTotalAmount' => $waitRefundTotalAmount,
            // 已回款总金额
            'refundTotalAmount'     => $refundTotalAmount,
            // 本月还款笔数
            'monthRefundCount'      => $monthRefundCount,
            // 本月还款金额
            'monthRefundAmount'     => $monthRefundAmount,
            // 激活红包金额
            'awardAmount'           => $awardAmount,
            //红包个数
            'awardNum'              => $awardNum,
            //加息券个数
            'ticketNum'             =>$TicketNum,
        ];

        // 待收本息
        $myFund['ca'] = $myFund['capital'] + $myFund['accrual'];

        // 我的总资产
        $myFund['totalMoney'] = $myFund['money'] + $myFund['ca'] + $myFund['money_freeze'];

        // 累计收益 = 累计已收利息 + 已激活红包
        $myFund['totalAccrual'] = $myFund['refundAccrual'] + $myFund['awardAmount'] +$TiyanItem;

        $tpldata = [
            // 账户资产组成
            'myFund'          => $myFund,
            // 回款计划
            'refund'          => $refundPlan,
            // 回款日历数据
            'refundCanlendar' => json_encode($refundPlan),
        ];
        return $tpldata;
    }
    /**
    *我的红包
     **/
    public function UserAccountsMyred($statue){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        return $this->mUserAward->UserAward($statue,$user_id);
    }

    /**
     * 我的加息券
     * @param $statue
     * @return mixed
     */
    public function UserAccountsMyticket($statue)
    {
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        return $this->mUserTicket->UserAccountsMyticket($statue,$user_id);
    }
    /**
     *我的消息
     **/
    public function UserAccountsOwnmesg(){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        return $this->mUserMessage->Ownmesg($user_id);
    }

    /**
     *我的消息
     **/
    public function Ownmesgcount(){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        return $this->mUserMessage->Ownmesgcount($user_id);
    }
    /**
     *我的消息
     **/
    public function Owncount(){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        return $this->mUserMessage->Owncount($user_id);
    }

    /**
     *删除
     **/
    public function UserMessageDelect($delitems){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        if(empty($delitems)){
            $mess['code'] = '2';
            $mess['mess'] = '请选择需要删除的内容';
            return $mess;
        }
        $deledata= $this->mUserMessage->UserMessageDelect($user_id,$delitems);
        if(empty($deledata)){
            $mess['code'] = '2';
            $mess['mess'] = '删除失败！！！';
            return $mess;
        }else{
            $mess['code'] = '1';
            $mess['mess'] = '删除成功！！！';
            return $mess;
        }
    }
    /**
     *标记
     **/
    public function UserAccountsBiao($delitems){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $datefist=$this->mUserMessage->UserAccountsFirst($user_id,$delitems);
        if(empty($datefist)){
            $mess['code'] = '2';
            $mess['mess'] = '没有未读信息';
            return $mess;
        }
        if(empty($delitems)){
            $mess['code'] = '2';
            $mess['mess'] = '请选择要操作的ID';
            return $mess;
        }
        for($i=0;$i<count($delitems);$i++){
            $auto_id = $delitems["$i"];
            $date=$this->mUserMessage->UserAccountsBiao($user_id,$auto_id);//查询ID是不是没有阅读的
            if(!empty($date)){
                $da=array(
                    'is_read'=>1
                );
             $biaodata=$this->mUserMessage->update($da,['auto_id'=>$auto_id]);
            }
        }
        if(empty($biaodata)){
            $mess['code'] = '2';
            $mess['mess'] = '标记失败！！！';
            return $mess;
        }else{
            $mess['code'] = '1';
            $mess['mess'] = '已标记！！！';
            return $mess;
        }
    }
    /**
     *标记
     **/
    public function UserAccountsBiaoes($delitems){
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        $datefist=$this->mUserMessage->UserAccountsFirstes($user_id,$delitems);
        if(empty($datefist)){
            $mess['code'] = '2';
            $mess['mess'] = '没有未读信息';
            return $mess;
        }
        $da=array(
            'is_read'=>1
        );
        $biaodata=$this->mUserMessage->update($da,['auto_id'=>$delitems]);
        if(empty($biaodata)){
            $mess['code'] = '2';
            $mess['mess'] = '标记失败！！！';
            return $mess;
        }else{
            $mess['code'] = '1';
            $mess['mess'] = '已标记！！！';
            return $mess;
        }
    }


    //-------------------------------------------充值--------------------------------------------
    /**
     * @return array
     * @throws Exception
     * 充值
     */
    public function UserAccountsRecharge(){
        //用户是否登录
        if(session_get(UserEnum::USER_INFO_USER_ID)){
            $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        }else{
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_NOT_LOGIN],
                ProfessionErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        // 获取个人资产
        $fund = $this->GetFund($user_id);
        // 充值条件
        $condition = UserEnum::condition();

        $tpldata = [
            // 用户资产
            'fund'      => $fund,
            // 最小充值金额
            'minAmount' => $condition['min_amount'],
        ];
        return $tpldata;
    }

    public function UserDepositRecharge($amount){

            // 检查充值条件
            $result = $this->_checkDeposit($amount);

            // 错误跳转地址
            $redirect = url('/user/deposit/index');

            if ($result != 200)
            {
                throw new Exception("$result", 400);
            }

            // 构建支付表单
            $result = $this->buildTrade(
                // 用户ID
                session_get(UserEnum::USER_INFO_USER_ID),
                // 支付金额
                $amount,
                // 业务说明
                'USER',
                // 是否移动端
                0,
                // 是否使用存管通支付接口
                false
            );

            // 构建失败
            if ($result != 200)
            {
                throw new Exception("$result", 400);
            }
//        $user_bankcard = $this->mBankCard->GetUserBankCard(session_get(UserEnum::USER_INFO_USER_ID));
//            $arr = [
//              'amount' => $amount/100,
//             'user_bankcard' => $user_bankcard,
//            ];
           return $amount/100;
        }


    /**
     * 支付成功
     */
    public function success($tradeNum)
    {

        // 查询出充值订单
        $trade = DB::table('deal_deposit')
            ->select('auto_id','trade_num','user_id','detail','amount','status')
            ->where('trade_num',$tradeNum)
            ->where('status','WAIT')
            ->first();

        if (!$trade)
        {
            return '支付订单不存在';
        }

        // 资金操作

        $result = DealService::instance()->carry(
            // 用户ID
            $trade->user_id,
            // 总资金
            $trade->amount,
            // 事件ID
            $trade->auto_id,
            // 交易类型
            'IN_DEPOSIT',
            // 交易资金明细
            ['MONEY_DEPOSIT' => $trade->amount],
            // 业务说明
            'DEPOSIT'
        );

        // 发送站内消息
        if ($result == 200)
        {
            // 更新订单状态
            $depositWhere  = [
                'auto_id' => $trade->auto_id,
                'status'  => 'WAIT',
            ];
            $updateDeposit = [
                'status'      => 'SUCCESS',
                'finish_time' => time(),
            ];

            $trade1 = DB::table('deal_deposit')->where($depositWhere)->update($updateDeposit);

            $this->send(
                // 接收者ID
                $trade->user_id,
                // 标题
                '充值成功',
                // 内容
                '尊敬的用户，您已成功充值'.number_format($trade->amount/100, 2).' 元，详情请到账户概况查看。'
            );
        }


        return $result;
    }

    /**
     * @param $amount
     * @return mixed
     * 充值判断
     */
    public function _checkDeposit($amount)
    {
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        //用户是否登录
        $user_info = $this->mUser->GetUserInfo($user_id);

        // 检查用户身份证是否认证
        if (empty(session_get(UserEnum::USER_INFO_SESSION_KEY)->is_idcard))
        {
            throw new Exception('为保证投资安全，请先完成实名认证', 400);
        }
        $user_bankcard = $this->mBankCard->GetUserBankCard($user_info->user_id);
        //检查银行卡
        if (empty($user_bankcard))
        {
            throw new Exception("您的账户还未绑定银行卡，无法进行提现", 400);
        }
        // 充值条件
        $condition = UserEnum::condition();
        // 检查充值金额
        if ($amount < $condition['min_amount'])
        {
            throw new Exception('每笔充值金额不少于2元, 并且不能有分、角', 400);
        }

        if ($amount%100 != 0)
        {
            throw new Exception("每笔充值金额不能含有分、角, 您输入的投资金额是".number_format($amount/100, 2)."元", 400);
        }

        if ($amount >= 1000000000)
        {
            throw new Exception('每笔充值金额不能超过 10,000,000 元', 400);
        }
        // 检查充值条件
        $check = UserEnum::check();

        if ($check['status'] != 200)
        {
            throw new Exception('服务器处理错误', 400);
        }
        return 200;
    }


//    /**
//     * @param $amount
//     * @return mixed
//     * 充值判断
//     */
//    public function _checkDeposit($amount)
//    {
//
//        // 检查用户身份证是否认证
//        if (!$_SESSION[UserEnum::USER_INFO_SESSION_KEY]->is_idcard)
//        {
//            throw new Exception('为保证投资安全，请先完成实名认证', 400);
//        }
//
//        // 充值条件
//        $condition = UserEnum::condition();
//
//        // 检查充值金额
//        if ($amount < $condition['min_amount'])
//        {
//            throw new Exception('每笔充值金额不少于2元, 并且不能有分、角', 400);
//        }
//
//        if ($amount%100 != 0)
//        {
//            throw new Exception("每笔充值金额不能含有分、角, 您输入的投资金额是".number_format($amount/100, 2)."元", 400);
//        }
//
//        if ($amount >= 1000000000)
//        {
//            throw new Exception('每笔充值金额不能超过 10,000,000 元', 400);
//        }
//
//        // 检查充值条件
//        $check = UserEnum::check();
//
//        if ($check['status'] != 200)
//        {
//            throw new Exception('服务器处理错误', 400);
//        }
//
//        return 200;
//    }

    /**
     * @param $userid
     * @param $amount
     * @param $detail
     * @param bool $isMobile
     * @param bool $isLazycat
     * @return mixed
     * 充值
     */
    public function buildTrade($userid, $amount, $detail, $isMobile = false, $isLazycat = true)
    {
        if (!array_key_exists($detail, StatusEnum::detail()))
        {
            throw new Exception("业务类型错误, 请稍后再试", 400);
        }

        $depositParams = [
            'detail' => '钢票网账户充值',
        ];

        // 固定富友支付
        $payType = 'FUIOU';

        // 移动端使用快捷支付, 否则为网关支付

        if ($isMobile)
        {
            $payWay   = 'SWIFT';
            $bankcard = $this->mBankCard->GetUserBankCard($userid);
            if (!$bankcard)
            {
                return '您的账户还未绑定银行卡';
            }
            $depositParams['bank_code'] = $bankcard->bank_code;
        }
        else
        {

            $payWay  = 'WEB';
        }

        // 创建订单号
        $tradeNum = StatusEnum::buildNumber('DEPOSIT');

        if (!$tradeNum)
        {
            return '订单号创建失败，请稍后再试';
        }
        $bankcard['auto_id'] = '';
        // 构建一张支付订单
        $trade = [
            // 订单号码
            'trade_num'=> $tradeNum,
            // 用户ID
            'user_id'  => $userid,
            // 银行卡ID
            //'bank_id'  => $bankcard['auto_id']?$bankcard['auto_id']:'',
            // 订单金额, 分为单位
            'amount'   => $amount,
            // 支付平台
            'pay_type' => $payType,
            // 支付方式
            'pay_way'  => $payWay,
            // 交易发起端
            'device'   => 'pc',
            // 业务类型
            'detail'   => $detail,
            // 订单状态
            'status'   => 'WAIT',
            // 创建时间
            'add_time' => time(),
        ];


        // 保存订单数据
        $tradeID =  DB::table('deal_deposit')->insertGetId($trade);
        if (!$tradeID)
        {
            return  '订单创建失败, 请稍后再试';
        }

        $trade['auto_id']  = $tradeID;

        //成功
        $fund_s = $this->success($tradeNum);
//        if ($isLazycat)
//        {
//            $payMilleware = \moon\middleware("payment\\Lazycat");
//        }
//        else
//        {
//            // 支付平台
//            $payType = ucfirst(strtolower($payType));
//            $payMilleware = \moon\middleware("payment\\{$payType}");
//        }

//        // 是否移动端
//        $payMilleware->isMobile = $isMobile;
//        // 设置订单
//        $payMilleware->trade    = $trade;
//        // 设置参数
//        $payMilleware->params   = $depositParams;
//
//        // 构建支付
//        $paydata = $payMilleware->build();

        if($fund_s!=200){
            return "$fund_s";
        }
        return 200;
    }

    public function AddUserFund($amount){

        $status = DB::table('user_fund')->increment('money_deposit',$amount);
        return 200;
    }


    //---------------------------------------------提现--------------------------------------------

    /**
     * @param $amount
     * @return mixed
     * 提现验证
     */
    public function _checkCash($amount)
    {
        $user_id = session_get(UserEnum::USER_INFO_USER_ID);
        //用户是否登录
        $user_info = $this->mUser->GetUserInfo($user_id);

        $user_bankcard = $this->mBankCard->GetUserBankCard($user_info->user_id);
        // 检查用户身份证是否认证
        if (!$user_info->is_idcard)
        {
            throw new Exception("为保证投资安全，请先完成实名认证", 400);
        }

         //检查银行卡
        if (empty($user_bankcard))
        {
            throw new Exception("您的账户还未绑定银行卡，无法进行提现", 400);
        }

        // 检查金额格式
        if ($amount <= 0)
        {
            throw new Exception('提现金额必须大于0元，您输入的是 '.$amount.' 元', 400);
        }

        // 检查提现条件
        $check = UserEnum::CashCheck();

        if ($check['status'] != 200)
        {
            throw new Exception('400', 400);
        }
        $cashFee = $this->getFee(session_get(UserEnum::USER_INFO_USER_ID), $amount);
        $fee     = $cashFee['data']['totalFee']?$cashFee['data']['totalFee']:0;
        if ($amount <= $fee)
        {
            throw new Exception('提现金额小于提现所需手续费，无法进行提现，提现所需手续费为：'.number_format($fee/100,2).' 元', 400);
        }

       $data = $cashFee?$cashFee:'';

        return ['status'=>200,'data'=>$data];
    }

    /**
     * @param $amount
     * 提现
     */
   public function UserCashRecharge($amount){

       $user_id = session_get(UserEnum::USER_INFO_USER_ID);
       // 检查提现条件
       $cashFee  = $this->_checkCash($amount);

       // 错误跳转地址
       $redirect = url('/user/cash/index');

       if ($cashFee['status'] != 200)
       {
           return 400;
       }

       $feeDetail = $cashFee['data']['data'];

       $bankcard  = $this->GetUserBankCard($user_id);
       // 创建订单号
       $tradeNum = StatusEnum::buildNumber('CASH');

       if (!$tradeNum)
       {
           return  '订单号创建失败，请稍后再试';
       }
       // 创建提现订单
       $tableVal = [
           // 订单号码
         'trade_num'    => $tradeNum,
           //用户ID
         'user_id'      => $user_id,
           // 提现总金额
         'amount'       =>$amount,
           // 提现手续费
           'fee'        =>$feeDetail['totalFee'],
           // 手续费详情
        'fee_detail'    =>json_encode(['liveFee' => $feeDetail['liveFee'], 'depositFee' => $feeDetail['depositFee']]),
           // 银行卡ID
        'bankcard_id'   =>110110110110110110,
           // 设备
           'device'     =>'PC',
           //状态
           'status'    => 'WAIT',
           // 添加时间
           'add_time'  => time(),
       ];

       $trade = DB::table('deal_cash')->insert($tableVal);

       // 订单创建失败
       if (!$trade)
       {
           return 400;
       }
       $fund_s = $this->confirm($tradeNum);

       if($fund_s!=200){
           return "$fund_s";
       }
       $arr = [
           'amount' => $amount/100,
           'user_bankcard' => $bankcard,
       ];
       return $arr;
//       // 构建支付表单
//       $dealLazy = \moon\middleware('lazycat\\Deal');
//
//       $result = $dealLazy->withdraw(
//       // 订单号码
//           $trade['data']['trade_num'],
//           // 客户端
//           $this->request->isMobile()?'MOBILE':'PC',
//           // 用户ID
//           $this->_user['user_id'],
//           // 支付金额
//           $amount/100,
//           $feeDetail['totalFee']/100
//       );
//
//       // 构建失败
//       if ($result['status'] != 200)
//       {
//           return $this->error(400, $result['info'], $redirect);
//       }
//
//       list($url, $data) = $result['data'];
//
//       $tpldata = [
//           // 提交URL
//           'url'  => $url,
//           // 表单数据
//           'data' => $data,
//       ];
   }

    /**
     * @param $amount
     * @param $userid
     * 计算提现手续费
     */
    public function getFee($userid, $amount)
    {
        $fund = $this->GetFund($userid);

        // 检查余额
        if ($fund->money < $amount)
        {
            throw new Exception("余额不足，当前可用余额为 $fund->money_format 元", 400);
        }
        // 提现手续费配置
        $cashFactor = UserEnum::fee_factor();

        // 回款金额
        $liveAmount = $fund->money - $fund->money_deposit;

        // 回款及福利金额手续费
        $liveFee    = 0;
        // 充值未投资手续费
        $depositFee = 0;

        // 回款及福利金额最小手续费
        $minLiveFee = $cashFactor['money_live_fee_min']*100;
        // 充值未投资最小提现手续费
        $minDepositFee = $cashFactor['money_deposit_fee_min']*100;

        if ($amount <= $liveAmount)
        {
            // 实际回款提现金额
            $liveCashAmount = $amount;
            // 计算手续费
            $liveFee = ceil($liveCashAmount * $cashFactor['money_live_fee']);
            $liveFee = ($liveFee < $minLiveFee) ? $minLiveFee : $liveFee;
        }
        else
        {
            // 如果提取回款金额
            if ($liveAmount != 0)
            {
                $liveFee = $minLiveFee;
            }

            $depositCashAmount = $amount - $liveAmount;

            $depositFee = ceil($depositCashAmount * $cashFactor['money_deposit_fee']);
            $depositFee = ($depositFee < $minDepositFee) ? $minDepositFee : $depositFee;
        }

        // 每月两次免费机会
//        $isMonthFree = false;
//        if ($liveFee > 0)
//        {
//            $monthStartTime = strtotime(date('Y-m-').'1');
////            $cashWhere = [
////                'add_time' => ['>', $monthStartTime],
////                'user_id'  => $userid,
////                'status'   => ['<>', 'WAIT'],
////            ];
//            $thisMonthCount = DB::table('deal_cash')
//                ->where('user_id',$userid)
//                ->where('add_time','>',$monthStartTime)
//                ->whereIn('status','!=','WAIT')
//                ->count();
//
//            if ($cashFactor['month_free_count'] > $thisMonthCount)
//            {
//                $liveFee = 0;
//                $isMonthFree = true;
//            }
//        }

        // 预计到账金额
        $amountPlan = ($amount-$liveFee-$depositFee) > 0 ?($amount-$liveFee-$depositFee):0;

        $fee = [
            // 提现总金额
            'amount'     => $amount,
            // 回款及福利金额提现手续费
            'liveFee'    => $liveFee,
            // 充值未投资提现手续费
            'depositFee' => $depositFee,
            // 总手续费
            'totalFee'   => $liveFee+$depositFee,
            // 预计到账金额
            'amountPlan' => $amountPlan,
            // 月免费提现
            //'is_month_free'   => $isMonthFree,
            // 单位转为元
            'liveFee_unit'    => $liveFee/100,
            'depositFee_unit' => $depositFee/100,
            'totalFee_unit'   => ($liveFee+$depositFee)/100,
            'amountPlan_unit' => $amountPlan/100,
        ];


        return  ['data'=>$fee];
    }

    /**
     * 提现确认操作
     * 提现金额操作至冻结金额
     */
    public function confirm($tradeNum)
    {
        // 查询出提现订单
        // 查询出充值订单
        $trade = DB::table('deal_cash')
            ->select('auto_id','trade_num','user_id','amount','status')
            ->where('trade_num',$tradeNum)
            ->where('status','WAIT')
            ->first();

        // 存在订单 修改提现订单状态
        if (!$trade)
        {
            return  '提现订单不存在[确认提现]';
        }

        // 计算提现金额明细
        $fund   = $this->GetFund($trade->user_id);

        $amount = $trade->amount;
        // 使用的回款金额
        $returnAmount  = 0;
        // 使用的福利金额
        $awardAmount   = 0;
        // 使用的充值未投资金额
        $depositAmount = 0;

        // 首先使用回款金额
        if ($amount < $fund->money_return)
        {
            $returnAmount = $amount;
            $amount       = 0;
        }
        else
        {
            $returnAmount = $fund->money_return;
            $amount       = $amount - $returnAmount;
        }

        // 是否使用福利金额
        if ($amount > 0)
        {
            if ($amount < $fund->money_award)
            {
                $awardAmount = $amount;
                $amount      = 0;
            }
            else
            {
                $awardAmount = $fund->money_award;
                $amount      = $amount - $awardAmount;
            }
        }

        // 是否使用充值未投资金额
        if ($amount > 0)
        {
            if ($amount < $fund->money_deposit)
            {
                $depositAmount = $amount;
                $amount        = 0;
            }
            else
            {
                $depositAmount = $fund->money_deposit;
                $amount        = $amount - $depositAmount;
            }
        }

        // 资金操作明细
        $cashDetail    = ['MONEY_FREEZE' => $trade->amount];
        $returnAmount  && $cashDetail['MONEY_RETURN']  = -$returnAmount;
        $awardAmount   && $cashDetail['MONEY_AWARD']   = -$awardAmount;
        $depositAmount && $cashDetail['MONEY_DEPOSIT'] = -$depositAmount;
        $trade1 = DB::table('deal_cash')->where('auto_id',$trade->auto_id)->update(['status'=>'SUCCESS']);
        $result = DealService::instance()->carry(
            // 用户ID
            $trade->user_id,
            // 总资金
            -$trade->amount,
            // 事件ID
            $trade->auto_id,
            // 交易类型
            'DE_CASH',
            // 交易资金明细
            $cashDetail,
            // 业务说明
            'CASH'
        );

        // 更新为待确认状态
        $this->send(
        // 接收者ID
            $trade->user_id,
            // 标题
            '提现成功',
            // 内容
            '尊敬的用户，您于'.date('Y-m-d',time()).'申请的'.($trade->amount/100).'元提现已提交成功，将在T+1日到账，请注意查收'
        );

        return $result;
    }

    public function GetCashFee($amount){
        // 检查金额格式
        if ($amount <= 0)
        {
            return '提现金额必须大于0元，您输入的是 '.$amount.' 元';
        }
        $CashFee = $this->getFee(session_get(UserEnum::USER_INFO_USER_ID), $amount);
        if(empty($CashFee['status'])){
            return Response::json([
                'code' => 200,
                'msg'  => '成功!',
                'data' => $CashFee['data']
            ]);
        }else{
            return Response::json([
                'code' => $CashFee['status'],
                'msg'  => $CashFee['msg'],
                'data' => ''
            ]);
        }

    }

    /**
     * @param $userid
     * @param $title
     * @param $content
     * @return bool
     * 发送用户通知
     */
    public static function send($userid, $title, $content)
    {
        if (!$userid)
        {
            return false;
        }
        return DB::table('user_message')->insert([
                'user_id' => $userid,
                'title'   => $title,
                'content' => $content,
                'add_time'=> time(),
            ]
        );

    }

    /**
     * @param $userid
     * @return bool
     * 获取用户银行卡
     */
    public function GetUserBankCard($userid)
    {
        if (!$userid)
        {
            return false;
        }
       return $this->mBankCard->GetUserBankCard($userid);

    }

    /**
     * @return bool
     * 邀请推广列表
     */
    public function InvitePromotion()
    {
        //邀请好友期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $user_list = $this->mUser->InviteUserList($phase[$Last_phase]['end_time']);
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];

        foreach($user_list as $k=>$v){
            $userid[] = $v->user_id;
//            $Invite_id = $this->mUser->UserInviteId($v->user_id,$time);
//             $count = count($Invite_id);
//            $user_list[$k]->count = $count;
//            $InvId = array();
//            if($count==0){
//                unset($user_list[$k]);
//            }else{
//                foreach($Invite_id as $vv){
//                    $InvId[] = $vv->user_id;
//                }
//                $amount = $this->mInvest->UserInviteAmount($InvId,$time);
//                $user_list[$k]->amount = $amount;
//            }
        }
        $str_userid = implode(',',$userid);
        $count = DB::select("select parent_id,count(1) as count from gpw_user  where parent_id in ($str_userid) and add_time between $time[0] and $time[1] group by gpw_user.parent_id");
        $Invite_id = $this->mUser->UserInviteId1($userid,$time);
        foreach($Invite_id as $vv){
                    $InvId[] = $vv->user_id;
                }
        $str_id = implode(',',$InvId);
        $amount = DB::select("select parent_id,sum(amount) as amount from gpw_invest left join gpw_user on gpw_user.user_id = gpw_invest.user_id where gpw_invest.user_id in ($str_id) and gpw_invest.add_time between $time[0] and $time[1] group by gpw_user.parent_id");
        foreach($user_list as $k=>$v){
            foreach($count as $vv){
                if($vv->parent_id==$v->user_id){
                        $vv->telephone = $v->telephone;
                        $vv->name      = $v->name;
                    foreach($amount as $vvv){
                        if($vv->parent_id==$vvv->parent_id){
                                $vv->amount = $vvv->amount;
                        }else{
                            $vv->amount = 0;
                        }
                    }
                }
            }
        }
        return $count;
    }


    /**
     * @param $userid
     * @return bool
     * 邀请用户详情
     */
    public function UserInviteInfo($userid)
    {
        //邀请好友期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        //所有被邀请用户ID
        $Invite_id = $this->mUser->UserInviteId($userid,$time);
        foreach($Invite_id as $v){
            $InvId[] = $v->user_id;
        }
        $info = $this->mInvest->UserInviteInfo($InvId,$time);
        $count = count($InvId);
        $amount = $this->mInvest->UserInviteAmount($InvId,$time);
        $fieldInfo = [
            '被邀请人ID',
            '手机',
            '投资金额',
            '投资时间',
        ];
        $data = [
           'fieldInfo' =>$fieldInfo,
            'info'     =>$info,
            'count'    =>$count,
            'amount'   =>$amount,
        ];
        return $data;

    }

    /**
     * 邀请好友人数查询
     * @param $user_id
     * @return mixed
     */
    public function InviteCount($user_id)
    {
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        return $this->mUser->InviteCount($user_id,$time);
    }

    /**
     * 邀请好友查询
     * @param $user_id
     * @return mixed
     */
    public function UserInvite($user_id,$page,$page_size)
    {
        //获取期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        //获取被邀请人信息
        $info = $this->mUser->UserInvite($user_id,$page,$page_size,$time);
        if(!empty($info)){
            //获取被邀请人ID
            foreach($info as $v){
                $userid[]=$v->user_id;
            }
            //获取邀请人投资记录
            $Invest_id = $this->mInvest->GetInviteInvest($userid,$time);
            //被邀请人投资总数
            $invest_amount = 0;
            //获取投资记录ID
            if(!empty($Invest_id)){
                foreach($Invest_id as $v){
                    $Investid[] = $v->user_id;
                }
                foreach($info as $v){
                    if(in_array($v->user_id,$Investid)){
                        $v->status = '已投资';

                    }else{
                        $v->status = '未投资';
                    }
                }
            }else{
                foreach($info as $v){
                    $v->status = '未投资';
                }
            }
        }
        //判断被邀请人投资状态
        return $info;
    }


    /**
     * 邀请好有返利
     * @param $user_id
     * @return mixed
     */
    public function InviteAmount($user_id)
    {
        //获取期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        //获取被邀请人信息
        $info = $this->mUser->InvestAmount($user_id,$time);
        $invite_amount = 0;
        if(!empty($info)){
            //获取被邀请人ID
            foreach($info as $v){
                $userid[]=$v->user_id;
            }
            //获取邀请人投资记录
            $Invest_id = $this->mInvest->GetInviteInvest($userid,$time);
            //被邀请人投资总数
            $invest_amount = 0;
            //获取投资记录ID
            if(!empty($Invest_id)){
                foreach($Invest_id as $v){
                    $Investid[] = $v->user_id;
                    $invest_amount += $v->amount;
                }
            }
            $invest_amount = $invest_amount/100;
            if($invest_amount>=3000 && $invest_amount<5000){
                $invite_amount = 5;
            }else if($invest_amount>=5000 && $invest_amount<10000){
                $invite_amount = 10;
            }else if($invest_amount>=10000 && $invest_amount<30000){
                $invite_amount = 25;
            }else if($invest_amount>=30000 && $invest_amount<60000){
                $invite_amount = 58;
            }else if($invest_amount>=60000 && $invest_amount<100000){
                $invite_amount = 126;
            }else if($invest_amount>=100000 && $invest_amount<200000){
                $invite_amount = 258;
            }else if($invest_amount>=200000){
                $invite_amount = 518;
            }
        }
        //判断被邀请人投资状态
        return $invite_amount;
    }


}